/**
 * @(#)HttpProxyUtils.java 2016年7月21日
 * Copyright(C) 2015 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package com.zhexinit.proxy.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhexinit.proxy.domain.HttpContext;
import com.zhexinit.proxy.domain.HttpProxyLog;
import com.zhexinit.proxy.domain.ProxyHost;

import edu.hziee.common.queue.DelayExecuteBuffer;

/**
 * TODO 请加入本类的说明
 * 
 * @author <a href="mailto:zhaihuilin@zhexinit.com" >翟惠林</a>
 * @version 1.0.0
 */
public class HttpProxyUtils {
	public static final Logger LOGGER = LoggerFactory.getLogger(HttpProxyUtils.class);

	public static final int SO_TIMEOUT = 50000;

	public static final int RETRY = 3;

	private static final int INIT_LIMIT_COUNT = 50;

	private static final int MAX_FILE_LEN = 10 * 1024;

	public static String httpPost(HttpProxyLog httpProxyLog, DelayExecuteBuffer<HttpProxyLog> httpProxyLogBuffer, boolean https) {
		for (int i = 0; i < RETRY; i++) {
			CloseableHttpClient client = null;
			if (https) {
				client = createHttpsClient();
			} else {
				client = HttpClients.custom().build();
			}
			long t = System.currentTimeMillis();

			HttpContext httpContext = httpProxyLog.getHttpContext();
			String provinceId = httpContext.getProvinceId();
			String imsi = httpContext.getImsi();
			ProxyHost proxyHost = ProxyHostUtils.getProxyHost(imsi, provinceId, INIT_LIMIT_COUNT, httpProxyLog.getHttpContext().getBizType());
			httpProxyLog.setIpConnect(proxyHost.getIp());
			httpProxyLog.getHeaderMap().put("Ip", proxyHost.getIp());
			String url = httpProxyLog.getUrl();
			HttpPost httpPost = new HttpPost(url);
			HttpHost proxy = new HttpHost(proxyHost.getAddress(), proxyHost.getPort());
			RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(SO_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
			httpPost.setConfig(config);
			LOGGER.info("request line:" + httpPost.getRequestLine());
			try {
				// 填写相关请求头信息和请求参数信息
				fillReqHeader(httpProxyLog, httpPost);
				fillReqParams(httpProxyLog, httpPost);
				HttpResponse httpResponse = client.execute(httpPost);
				fillRespHeaderAndBody(httpProxyLog, httpResponse);
				return httpProxyLog.getResponseContent();
			} catch (IOException e) {
				LOGGER.warn("http 代理请求失败 [{}]", httpProxyLog, e);
			} finally {
				long t1 = System.currentTimeMillis();
				httpProxyLog.setReadTime(t1 - t);
				httpProxyLogBuffer.add(httpProxyLog);
				httpPost.releaseConnection();
			}
		}
		return null;

	}

	public static String httpPostXml(HttpProxyLog httpProxyLog, String requestXml, DelayExecuteBuffer<HttpProxyLog> httpProxyLogBuffer, boolean https) {
		for (int i = 0; i < RETRY; i++) {
			CloseableHttpClient client = null;
			if (https) {
				client = createHttpsClient();
			} else {
				client = HttpClients.custom().build();
			}
			long t = System.currentTimeMillis();
			HttpContext httpContext = httpProxyLog.getHttpContext();
			String provinceId = httpContext.getProvinceId();
			String imsi = httpContext.getImsi();
			ProxyHost proxyHost = ProxyHostUtils.getProxyHost(imsi, provinceId, INIT_LIMIT_COUNT, httpContext.getBizType());
			httpProxyLog.setIpConnect(proxyHost.getIp());
			httpProxyLog.getHeaderMap().put("Ip", proxyHost.getIp());
			String url = httpProxyLog.getUrl();
			HttpPost httpPost = new HttpPost(url);
			LOGGER.debug("requestXml is " + requestXml);
			httpPost.setEntity(new StringEntity(requestXml, "utf-8"));
			HttpHost proxy = new HttpHost(proxyHost.getAddress(), proxyHost.getPort());
			RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(SO_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
			httpPost.setConfig(config);
			LOGGER.info("request line:" + httpPost.getRequestLine());
			try {
				fillReqHeader(httpProxyLog, httpPost);
				HttpResponse httpResponse = client.execute(httpPost);
				fillRespHeaderAndBody(httpProxyLog, httpResponse);
				return httpProxyLog.getResponseContent();
			} catch (IOException e) {
				LOGGER.warn("http 代理请求失败 [{}]", httpProxyLog, e);
			} finally {
				long t1 = System.currentTimeMillis();
				httpProxyLog.setReadTime(t1 - t);
				httpProxyLogBuffer.add(httpProxyLog);
				httpPost.releaseConnection();
			}
		}
		return null;
	}

	public static byte[] httpDownload(HttpProxyLog httpProxyLog, DelayExecuteBuffer<HttpProxyLog> httpProxyLogBuffer, boolean https) {
		for (int i = 0; i < RETRY; i++) {
			CloseableHttpClient client = null;
			if (https) {
				client = createHttpsClient();
			} else {
				client = HttpClients.custom().build();
			}
			HttpClientContext httpClientContext = null;
			HttpContext httpContext = httpProxyLog.getHttpContext();
			String provinceId = httpContext.getProvinceId();
			String imsi = httpContext.getImsi();
			ProxyHost proxyHost = ProxyHostUtils.getProxyHost(imsi, provinceId, INIT_LIMIT_COUNT, httpProxyLog.getHttpContext().getBizType());
			httpProxyLog.setIpConnect(proxyHost.getIp());
			httpProxyLog.getHeaderMap().put("Ip", proxyHost.getIp());

			long t = System.currentTimeMillis();

			String url = httpProxyLog.getUrl();
			HttpGet httpGet = new HttpGet(url);

			HttpHost proxy = new HttpHost(proxyHost.getAddress(), proxyHost.getPort());

			RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(SO_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
			httpGet.setConfig(config);
			LOGGER.info("request line:" + httpGet.getRequestLine());
			try {
				// 填写相关请求头信息和请求参数信息
				fillReqHeader(httpProxyLog, httpGet);
				HttpResponse httpResponse = client.execute(httpGet, httpClientContext);
				byte[] responseBody = EntityUtils.toByteArray(httpResponse.getEntity());
				httpProxyLog.setResponseContentBytes(responseBody);
				fillRespHeader(httpProxyLog, httpResponse);

				return responseBody;
			} catch (IOException e) {
				LOGGER.warn("http 代理请求失败 [{}]", httpProxyLog, e);
			} finally {
				long t1 = System.currentTimeMillis();
				httpProxyLog.setReadTime(t1 - t);
				httpProxyLogBuffer.add(httpProxyLog);
				httpGet.releaseConnection();
			}
		}
		return null;
	}

	public static String httpGet(HttpProxyLog httpProxyLog, DelayExecuteBuffer<HttpProxyLog> httpProxyLogBuffer, RedisClient redisClient) {
		String url = httpProxyLog.getUrl();
		boolean https = false;
		if (url.indexOf("https") > -1) {
			https = true;
		}
		for (int i = 0; i < RETRY; i++) {
			CloseableHttpClient client = null;
			if (https) {
				client = createHttpsClient();
			} else {
				client = HttpClients.custom().build();
			}
			HttpClientContext httpClientContext = null;
			HttpContext httpContext = httpProxyLog.getHttpContext();
			String provinceId = httpContext.getProvinceId();
			String imsi = httpContext.getImsi();
			String proxyHostIpKey = CacheKey.PROXY_HOST_IP_MISI + "_" + imsi + "_" + DateUtil.getCurrentDateStr();
			Object oproxyip = redisClient.get(proxyHostIpKey);
			String oldproxyip = "";
			if (oproxyip != null) {
				oldproxyip = oproxyip.toString();
			}
			ProxyHost proxyHost = ProxyHostUtils.getProxyHost(imsi, provinceId, INIT_LIMIT_COUNT, httpProxyLog.getHttpContext().getBizType());
			LOGGER.info("", proxyHost.getIp());
			if (StringUtils.isNotBlank(oldproxyip) && !oldproxyip.equals(proxyHost.getIp())) {
				LOGGER.warn("oldproxyip is [{}],proxyHost.getIp is [{}]", oldproxyip, proxyHost.getIp());
				break;
			}
			httpProxyLog.setIpConnect(proxyHost.getIp());
			httpProxyLog.getHeaderMap().put("Ip", proxyHost.getIp());
			long t = System.currentTimeMillis();

			String queryString = getQueryString(httpProxyLog);
			if (StringUtils.isNotBlank(queryString)) {
				if (url.indexOf("?") > 0) {
					url += "&";
				} else {
					url += "?";
				}
				url += queryString;
			}
			HttpGet httpGet = new HttpGet(url);

			HttpHost proxy = new HttpHost(proxyHost.getAddress(), proxyHost.getPort());
			RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(SO_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
			httpGet.setConfig(config);
			LOGGER.info("request line:" + httpGet.getRequestLine());
			try {
				// 填写相关请求头信息和请求参数信息
				fillReqHeader(httpProxyLog, httpGet);
				HttpResponse httpResponse = client.execute(httpGet, httpClientContext);

				if (StringUtils.isBlank(oldproxyip)) {
					redisClient.put(proxyHostIpKey, proxyHost.getIp(), 86400);
				}

				fillRespHeaderAndBody(httpProxyLog, httpResponse);
				if (httpResponse.getStatusLine().getStatusCode() == 302) {
					Header location = httpResponse.getFirstHeader("Location");
					String locationUrl = location.getValue();
					HttpProxyLog httpProxyLog2 = new HttpProxyLog();
					try {
						BeanUtils.copyProperties(httpProxyLog2, httpProxyLog);
					} catch (IllegalAccessException e) {
						LOGGER.warn("Any warn msg that u want to write", e);
					} catch (InvocationTargetException e) {
						LOGGER.warn("Any warn msg that u want to write", e);
					}
					httpProxyLog2.setUrl(locationUrl);
					return httpGet(httpProxyLog2, httpProxyLogBuffer, redisClient);
				}

				return httpProxyLog.getResponseContent();
			} catch (IOException e) {
				LOGGER.warn("http 代理请求失败 [{}]", httpProxyLog, e);
			} finally {
				long t1 = System.currentTimeMillis();
				httpProxyLog.setReadTime(t1 - t);
				httpProxyLogBuffer.add(httpProxyLog);
				httpGet.releaseConnection();
			}
		}
		return null;
	}

	public static byte[] httpDownload(HttpProxyLog httpProxyLog, DelayExecuteBuffer<HttpProxyLog> httpProxyLogBuffer, RedisClient redisClient) {
		String url = httpProxyLog.getUrl();
		boolean https = false;
		if (url.indexOf("https") > -1) {
			https = true;
		}
		for (int i = 0; i < RETRY; i++) {
			CloseableHttpClient client = null;
			if (https) {
				client = createHttpsClient();
			} else {
				client = HttpClients.custom().build();
			}
			HttpClientContext httpClientContext = null;
			HttpContext httpContext = httpProxyLog.getHttpContext();
			String provinceId = httpContext.getProvinceId();
			String imsi = httpContext.getImsi();
			// 创造imsi key
			String proxyHostIpKey = CacheKey.PROXY_HOST_IP_MISI + "_" + imsi + "_" + DateUtil.getCurrentDateStr();
			Object oproxyip = redisClient.get(proxyHostIpKey);
			String oldproxyip = "";
			if (oproxyip != null) {
				oldproxyip = oproxyip.toString();
			}
			ProxyHost proxyHost = ProxyHostUtils.getProxyHost(imsi, provinceId, INIT_LIMIT_COUNT, httpProxyLog.getHttpContext().getBizType());
			LOGGER.info("", proxyHost.getIp());
			if (StringUtils.isNotBlank(oldproxyip) && !oldproxyip.equals(proxyHost.getIp())) {
				LOGGER.warn("oldproxyip is [{}],proxyHost.getIp is [{}]", oldproxyip, proxyHost.getIp());
				break;
			}
			httpProxyLog.setIpConnect(proxyHost.getIp());
			httpProxyLog.getHeaderMap().put("Ip", proxyHost.getIp());

			long t = System.currentTimeMillis();

			HttpGet httpGet = new HttpGet(url);

			HttpHost proxy = new HttpHost(proxyHost.getAddress(), proxyHost.getPort());

			RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(SO_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
			httpGet.setConfig(config);
			LOGGER.info("request line:" + httpGet.getRequestLine());
			try {
				// 填写相关请求头信息和请求参数信息
				fillReqHeader(httpProxyLog, httpGet);
				HttpResponse httpResponse = client.execute(httpGet, httpClientContext);

				if (StringUtils.isBlank(oldproxyip)) {
					redisClient.put(proxyHostIpKey, proxyHost.getIp(), 86400);
				}

				byte[] responseBody = EntityUtils.toByteArray(httpResponse.getEntity());
				httpProxyLog.setResponseContentBytes("success".getBytes());
				fillRespHeader(httpProxyLog, httpResponse);

				return responseBody;
			} catch (IOException e) {
				LOGGER.warn("http 代理请求失败 [{}]", httpProxyLog, e);
			} finally {
				long t1 = System.currentTimeMillis();
				httpProxyLog.setReadTime(t1 - t);
				httpProxyLogBuffer.add(httpProxyLog);
				httpGet.releaseConnection();
			}
		}
		return null;
	}

	public static void fillRespHeader(HttpProxyLog httpProxyLog, HttpResponse httpResponse) {
		Header[] headers = httpResponse.getAllHeaders();
		for (Header header : headers) {
			httpProxyLog.getResponseHeaderMap().put(header.getName(), header.getValue());
		}
		setCookieMap(httpResponse, httpProxyLog.getHttpContext().getCookies());
		int responseCode = httpResponse.getStatusLine().getStatusCode();
		httpProxyLog.setResponseCode(responseCode);
	}

	private static void fillRespHeaderAndBody(HttpProxyLog httpProxyLog, HttpResponse httpResponse) throws IllegalStateException, IOException {
		Header[] headers = httpResponse.getAllHeaders();

		for (Header header : headers) {
			httpProxyLog.getResponseHeaderMap().put(header.getName(), header.getValue());
		}
		setCookieMap(httpResponse, httpProxyLog.getHttpContext().getCookies());

		int responseCode = httpResponse.getStatusLine().getStatusCode();

		String responseContent = readNoBigFile(httpResponse.getEntity().getContent(), httpProxyLog.getResponseHeaderMap());
		if (StringUtils.isNotBlank(responseContent) && responseContent.length() > 4096) {
			responseContent = responseContent.substring(0, 4096);
		}
		httpProxyLog.setResponseCode(responseCode);
		httpProxyLog.setResponseContent(responseContent);
	}

	/**
	 * 
	 * 最多只读取MAX_FILE_LEN字节
	 * 
	 * @author <a href="mailto:zhouchao@zhexinit.com" >周超</a>
	 * @param in
	 * @param headMap
	 * @return
	 * @throws IOException
	 */
	public static String readNoBigFile(InputStream in, Map<String, String> headMap) throws IOException {
		StringBuilderWriter sw = new StringBuilderWriter();
		InputStreamReader input = new InputStreamReader(in);
		copyLarge(input, sw);
		sw.close();
		return sw.toString();
	}

	public static void copyLarge(Reader input, Writer output) throws IOException {
		char[] buffer = new char[1 * 1024];
		long count = 0;
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
			if (count >= MAX_FILE_LEN) {
				LOGGER.error("代理请求传过来内容大于10k，丢弃多余的数据");
				break;
			}
		}
	}

	private static String getQueryString(HttpProxyLog httpProxyLog) {
		if (httpProxyLog.getParamMap().isEmpty())
			return null;
		String queryString = "";

		for (Map.Entry<String, String> entry : httpProxyLog.getParamMap().entrySet()) {
			try {
				queryString += "&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				LOGGER.warn("Any warn msg that u want to write", e);
			}
		}
		if (queryString.length() > 0) {
			queryString = queryString.substring(1);
		}
		return queryString;

	}

	private static void fillReqParams(HttpProxyLog httpProxyLog, HttpPost httpPost) {
		if (httpProxyLog.getParamMap().isEmpty())
			return;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : httpProxyLog.getParamMap().entrySet()) {
			NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
			params.add(nameValuePair);
		}

		UrlEncodedFormEntity postEntity;
		try {
			postEntity = new UrlEncodedFormEntity(params, "UTF-8");
			httpPost.setEntity(postEntity);
		} catch (UnsupportedEncodingException e) {
			LOGGER.warn("Any warn msg that u want to write", e);
		}
	}

	private static void fillReqHeader(HttpProxyLog httpProxyLog, HttpRequest httpRequest) {

		for (Map.Entry<String, String> header : httpProxyLog.getHeaderMap().entrySet()) {
			httpRequest.addHeader(header.getKey(), header.getValue());
		}
		if (httpProxyLog.getHttpContext().getCookies() != null && !httpProxyLog.getHttpContext().getCookies().isEmpty()) {
			httpRequest.addHeader("Cookie", getCookies(httpProxyLog.getHttpContext().getCookies()).toString());
		}

	}

	/**
	 * 
	 * 描述：从浏览器响应中获取cookie数据存入map 编写者：袁淼 创建时间：2016年1月19日 下午4:09:38
	 * </pre>
	 * 
	 * @param httpResponse
	 * @param cookieMap
	 */
	private static void setCookieMap(HttpResponse httpResponse, Map<String, String> cookieMap) {

		HeaderElementIterator it = new BasicHeaderElementIterator(httpResponse.headerIterator("Set-Cookie"));
		while (it.hasNext()) {
			HeaderElement elem = it.nextElement();
			cookieMap.put(elem.getName(), elem.getValue());
			LOGGER.debug(elem.getName() + " = " + elem.getValue());
		}
	}

	/**
	 * 
	 * 描述：将用map存储的cookie转换成字符串格式的cookie 编写者：袁淼 创建时间：2016年1月19日 下午3:48:30
	 * </pre>
	 * 
	 * @param cookies
	 * @return
	 */
	private static StringBuilder getCookies(Map<String, String> cookies) {
		StringBuilder cookieBuilder = new StringBuilder();
		for (Map.Entry<String, String> entry : cookies.entrySet()) {
			cookieBuilder.append(entry.getKey() + "=" + entry.getValue() + ";");
		}
		LOGGER.debug("SETCOOKIES cookieMap[{}], cookieBuilder[{}]", new Object[] { cookies, cookieBuilder });
		return cookieBuilder;
	}

	private static CloseableHttpClient createHttpsClient() {

		SSLContext sslcontext = null;
		try {
			sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		} catch (KeyManagementException e) {
			LOGGER.warn("Any warn msg that u want to write", e);
		} catch (NoSuchAlgorithmException e) {
			LOGGER.warn("Any warn msg that u want to write", e);
		} catch (KeyStoreException e) {
			LOGGER.warn("Any warn msg that u want to write", e);
		}
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		CookieStore cookieStore = new BasicCookieStore();
		RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
		HttpClientContext context = HttpClientContext.create();
		context.setCookieStore(cookieStore);
		CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).setSSLSocketFactory(sslsf).build();

		return client;
	}

	public static String httpGet(HttpProxyLog httpProxyLog, DelayExecuteBuffer<HttpProxyLog> httpProxyLogBuffer, boolean https) {
		for (int i = 0; i < RETRY; i++) {
			CloseableHttpClient client = null;
			if (https) {
				client = createHttpsClient();
			} else {
				client = HttpClients.custom().build();
			}
			HttpClientContext httpClientContext = null;
			HttpContext httpContext = httpProxyLog.getHttpContext();
			String provinceId = httpContext.getProvinceId();
			String imsi = httpContext.getImsi();
			ProxyHost proxyHost = ProxyHostUtils.getProxyHost(imsi, provinceId, INIT_LIMIT_COUNT, httpProxyLog.getHttpContext().getBizType());
			LOGGER.info("", proxyHost.getIp());
			httpProxyLog.setIpConnect(proxyHost.getIp());
			httpProxyLog.getHeaderMap().put("Ip", proxyHost.getIp());
			long t = System.currentTimeMillis();

			String url = httpProxyLog.getUrl();

			String queryString = getQueryString(httpProxyLog);
			if (StringUtils.isNotBlank(queryString)) {
				if (url.indexOf("?") > 0) {
					url += "&";
				} else {
					url += "?";
				}
				url += queryString;
			}
			HttpGet httpGet = new HttpGet(url);

			HttpHost proxy = new HttpHost(proxyHost.getAddress(), proxyHost.getPort());
			RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(SO_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
			httpGet.setConfig(config);
			LOGGER.info("request line:" + httpGet.getRequestLine());
			try {
				// 填写相关请求头信息和请求参数信息
				fillReqHeader(httpProxyLog, httpGet);
				HttpResponse httpResponse = client.execute(httpGet, httpClientContext);
				fillRespHeaderAndBody(httpProxyLog, httpResponse);
				if (httpResponse.getStatusLine().getStatusCode() == 302) {
					Header location = httpResponse.getFirstHeader("Location");
					String locationUrl = location.getValue();
					HttpProxyLog httpProxyLog2 = new HttpProxyLog();
					try {
						BeanUtils.copyProperties(httpProxyLog2, httpProxyLog);
					} catch (IllegalAccessException e) {
						LOGGER.warn("Any warn msg that u want to write", e);
					} catch (InvocationTargetException e) {
						LOGGER.warn("Any warn msg that u want to write", e);
					}
					httpProxyLog2.setUrl(locationUrl);
					return httpGet(httpProxyLog2, httpProxyLogBuffer, https);
				}

				return httpProxyLog.getResponseContent();
			} catch (IOException e) {
				LOGGER.warn("http 代理请求失败 [{}]", httpProxyLog, e);
			} finally {
				long t1 = System.currentTimeMillis();
				httpProxyLog.setReadTime(t1 - t);
				httpProxyLogBuffer.add(httpProxyLog);
				httpGet.releaseConnection();
			}
		}
		return null;
	}
}
